package com.licheedev.screenpower

import android.content.Context
import android.os.PowerManager
import android.util.Log
import com.chrisplus.rootmanager.RootManager

/**
 * 使用root去息屏/亮屏
 * 参考 [https://blog.csdn.net/black_bird_cn/article/details/79717245](https://blog.csdn.net/black_bird_cn/article/details/79717245)
 * */
class RootScreenPower(private val context: Context) {

    companion object {
        private const val TAG = "ScreenPowerHelper"
        private const val TOUCH_POWER_KEY = "input keyevent 26"
        private const val TOUCH_SCREEN_OFF_KEY = "input keyevent 223"
        private const val TOUCH_SCREEN_ON_KEY = "input keyevent 224"
    }

    private val app = context.applicationContext
    private val powerManager = app.getSystemService(Context.POWER_SERVICE) as PowerManager

    private val rootManager: RootManager get() = RootManager.getInstance()

    /** 屏幕息屏 */
    fun screenOff() {
        if (rootManager.hasRooted()) {
            rootManager.runCommand(TOUCH_SCREEN_OFF_KEY)
        } else {
            Log.w(TAG, "您的手机还未获取root权限")
        }
    }


    /** 屏幕亮屏 */
    fun screenOn() {

        // if (rootManager.hasRooted()) {
        //     rootManager.runCommand(TOUCH_SCREEN_ON_KEY)
        // } else {
        //     Log.w(TAG, "您的手机还未获取root权限")
        // }

        // NOTE:使用这种方法，亮屏会比上面模拟按键的迅速
        val wakeLock = powerManager.newWakeLock(
            PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_DIM_WAKE_LOCK,
            "${app.packageName}:ScreenOn"
        )

        if (!powerManager.isScreenOn) {
            //屏幕会持续点亮
            wakeLock.acquire()
            wakeLock.release()
        }
    }


}